import { defineStore } from "pinia";
import { loginAPI, registerAPI, logoutAPI, getUserInfo, setUserPassward } from '@/api/modules/user.js'
import { getToken, setToken, setExpiresIn, removeToken } from '@/utils/auth.js'
import md5 from 'js-md5'

const useStore = defineStore("user", {
	unistorage: true, // 是否持久化
	state: () => ({
		userInfo: null, // 存储用户信息
		token: '' // 存储用户登录状态
	}),
	actions: {
		// 登录
		login(form) {
			const { loginName, password } = form
			const config = { loginName, password: btoa(password) };
			console.log(this.token, this.userInfo)
			return new Promise((resolve, reject) => {
				loginAPI(config).then(res => {
					let { token, ...info } = res.data
					this.userInfo = info
					this.token = token
					setToken(info.accessToken) // 保存token
					setExpiresIn(info.expireTime) // 保存结束cookie结束时间戳
					this.getInfo(info.userId)
					resolve(res)
				}).catch(err => {
					reject(error)
				})
			})
		},
		// 退出登录
		LogOut() {
			console.log(this.token, this.userInfo)
			logoutAPI().then(() => {
				this.userInfo = null
				this.token = '' 
				removeToken() // 删除token
				removeExpiresIn() // 删除结束时间戳
				resolve()
			}).catch(error => {
				reject(error)
			})
		},
		// 获取用户信息
		getInfo(userId) {
			getUserInfo(userId).then(res => {
				console.log(res)
				this.userInfo = Object.assign(this.userInfo, res.data)
			})
		}, 
		// 注册
		register(form) {
			const { rePassword, password, ...infoForm } = form
			const config = { password: btoa(password), ...infoForm };
			console.log(config)
			return new Promise((resolve, reject) => {
				registerAPI(config).then(res => {
					resolve(res)
				}).catch(err => {
					reject(err)
				})
			})
		},
		// 修改用户信息
		editUser(form) {
			const { currentPassword, newPassword } = form
			const config = { currentPassword, newPassword, userId: this.userInfo.userId }
			return new Promise((resolve, reject) => {
				getUserPassward(config).then(() => {
					// 修改成功, 重新登录
					this.LogOut()
				}).catch(() => {
					
				})
			})
		}
	},
	unistorage: {
		key: "user", // 缓存的键，默认为该 store 的 id
		paths: [ "userInfo", "token"], // 需要缓存的路径
	},
})

export default useStore